package com.jt.service;

import com.jt.vo.ImageVO;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashSet;
import java.util.Set;
import java.util.UUID;

@Service
@PropertySource(value = "classpath:/properties/image.properties",encoding = "UTF-8")
public class FileServiceImpl implements FileService {
    @Value("${image.fileDir}")
    private   String fileDir;
    @Value("${image.urlPath}")
    private String urlPath;
    private static Set<String> typeSet = new HashSet<>();

    static {
        typeSet.add(".jpg");
        typeSet.add(".png");
        typeSet.add(".gif");
    }

    @Override
    public ImageVO upload(MultipartFile uploadFile) {
        //获取文件名称
        String fileName = uploadFile.getOriginalFilename();
        //统一转换为小写
        fileName = fileName.toLowerCase();
        //根据点 截取图片格式
        int index = fileName.lastIndexOf(".");
        //
        String fileType = fileName.substring(index);
        if (!typeSet.contains(fileType)) {
            return ImageVO.fail();
        }
        try {
            BufferedImage bufferedImage  = ImageIO.read(uploadFile.getInputStream());
            int width = bufferedImage .getWidth();
            int  height = bufferedImage .getHeight();
            if (width == 0 || height == 0) {
                return ImageVO.fail();
            }
            String dateDir = new SimpleDateFormat("/yyyy/MM/dd/").format(new Date());
            String fileDirPath = fileDir + dateDir;
            File dirFile = new File(fileDirPath);
            if (!dirFile.exists()) {
                dirFile.mkdirs();
            }
            String uuid= UUID.randomUUID().toString().replace("-", "");
            String uuidName =uuid+fileType;
            File realFile = new File(fileDirPath+uuidName);
            uploadFile.transferTo(realFile);
           /* String url ="https://img14.360buyimg.com/n1/s450x450_jfs/t1/151857/40/2398/38943/5f8842b9Edac7df98/0a8a77bfea24aa1d.jpg";*/
            String url =urlPath+dateDir+uuidName;
            return ImageVO.success(url, width, height);
        } catch (IOException e) {
            e.printStackTrace();
            return ImageVO.fail();
        }
    }
}
